Component({
  data: {
    selected: 0,
    color: '#999999',
    selectedColor: '#007aff',
    list: [
      {
        pagePath: '/pages/bill/bill',
        text: '明细',
        iconPath: '/icon/gongzimingxi.png',
        selectedIconPath: '/icon/gongzimingxi.png'
      },
      {
        pagePath: '/pages/reportform/reportform',
        text: '图表',
        iconPath: '/icon/tubiaozhutu.png',
        selectedIconPath: '/icon/tubiaozhutu.png'
      },
      {
        pagePath: '/pages/record/record',
        text: '记一笔',
        iconPath: '/icon/add.png',
        selectedIconPath: '/icon/add.png',
        isSpecial: true
      },
      {
        pagePath: '/pages/index/index',
        text: '账单',
        iconPath: '/icon/zhangdanchaxun.png',
        selectedIconPath: '/icon/zhangdanchaxun.png'
      },
      {
        pagePath: '/pages/userConsole/userConsole',
        text: '我的',
        iconPath: '/icon/yonghu.png',
        selectedIconPath: '/icon/yonghu.png'
      }
    ]
  },
  
  attached() {
    // 获取当前页面路径
    const pages = getCurrentPages();
    if (pages.length === 0) {
      // 如果页面栈为空，设置默认选中项
      this.setData({
        selected: 0
      });
      return;
    }
    
    const currentPage = pages[pages.length - 1];
    if (!currentPage || !currentPage.route) {
      // 如果当前页面或路由不存在，设置默认选中项
      this.setData({
        selected: 0
      });
      return;
    }
    
    const currentRoute = '/' + currentPage.route;
    
    // 设置当前选中的tab
    const selected = this.data.list.findIndex(item => item.pagePath === currentRoute);
    this.setData({
      selected: selected !== -1 ? selected : 0
    });
  },
  
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      const index = data.index;
      
      // 如果点击的是当前页面，不进行跳转
      if (this.data.selected === index) {
        return;
      }
      
      wx.switchTab({
        url,
        success: () => {
          this.setData({
            selected: index
          });
        }
      });
    }
  }
});